package com.edgclub.edg.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.BBCommentImageAdapter;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.UploadApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.Reply;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.ReplyCommentData;
import com.edgclub.edg.task.GzReplyImageUpload;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.easeui.model.ReplyImageInfo;
import com.rockerhieu.emojicon.EmojiconEditText;
import com.rockerhieu.emojicon.EmojiconGridFragment;
import com.rockerhieu.emojicon.EmojiconsFragment;
import com.rockerhieu.emojicon.emoji.Emojicon;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;
import java.util.HashMap;

import me.nereo.multi_image_selector.bean.Image;


public class GzTopicReplyTopicActivity extends GzBaseTooolBarActivity implements
		OnClickListener, EmojiconGridFragment.OnEmojiconClickedListener,
		EmojiconsFragment.OnEmojiconBackspaceClickedListener,
		BBCommentImageAdapter.CloseclickListener,VolleyListener {

	private static final int REQUEST_IMAGE = 2;

	private EmojiconEditText et_sendreply;
	private LinearLayout li;
	private LinearLayout bar_bottom;
	private Button btn_send;
	private TopicApi topicApi;
	private UploadApi uploadApi;

//	private Topic topic;
	private String content;
	private String topicId;

	private User user;

	private LinearLayout ll_back , see_old;
	private ImageView iv_emoticons_normal,iv_keyboard_normal,iv_photo,iv_select_photo;
	private FrameLayout emojiconslayout;
	private LinearLayout ll_photo;
	private RecyclerView horizontal_listView;
	private TextView tv_image_num,tv_num;
	private BBCommentImageAdapter commentImageAdapter;

	private InputMethodManager manager;

	private ArrayList<ReplyImageInfo> infos;
	private ArrayList<Image> selectPathList;
	public static int maxImageCount = 9;

	private boolean ishasAlbum = false;
	private Reply clickreply; //评论
	private boolean isReplyComment;//是否是回复的回复
	private int clickposition;//评论的position

	private Reply reply;


	@Override
	public int getContentView() {
		return R.layout.activity_gz_topic_reply;
	}

	@Override
	public void setTitleBarView() {
	}

	@Override
	public void initView() {
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).register(this);
		li = (LinearLayout) findViewById(R.id.linear);
		li.setBackgroundColor(Color.TRANSPARENT);
		li.setOnClickListener(this);
		ll_back = (LinearLayout) findViewById(R.id.ll_back);
		see_old = (LinearLayout) findViewById(R.id.see_old);
		ll_back.setOnClickListener(this);
		see_old.setOnClickListener(this);
		bar_bottom = (LinearLayout) findViewById(R.id.bar_bottom);
		et_sendreply = (EmojiconEditText) findViewById(R.id.et_sendreply);
		et_sendreply.setCursorVisible(true);
		et_sendreply.setOnClickListener(this);
		btn_send = (Button) findViewById(R.id.btn_send);
		btn_send.setOnClickListener(this);
		iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal);
		iv_emoticons_normal.setOnClickListener(this);
		emojiconslayout = (FrameLayout) findViewById(R.id.emojicons);
		iv_photo = (ImageView) findViewById(R.id.iv_photo);
		iv_photo.setOnClickListener(this);
		iv_select_photo = (ImageView) findViewById(R.id.iv_select_photo);
		iv_keyboard_normal = (ImageView) findViewById(R.id.iv_keyboard_normal);
		ll_photo = (LinearLayout) findViewById(R.id.ll_photo);
		iv_keyboard_normal.setOnClickListener(this);
		iv_select_photo.setOnClickListener(this);
		tv_image_num = (TextView) findViewById(R.id.tv_image_num);
		tv_num = (TextView) findViewById(R.id.tv_num);
		horizontal_listView = (RecyclerView) findViewById(R.id.horizontal_listView);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		horizontal_listView.setLayoutManager(layoutManager);
		commentImageAdapter = new BBCommentImageAdapter(this);
		horizontal_listView.setAdapter(commentImageAdapter);
		commentImageAdapter.setCloseclickListener(this);


		setEmojiconFragment(false);
		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		et_sendreply.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

			}

			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

			}

			@Override
			public void afterTextChanged(Editable editable) {
				if(!TextUtils.isEmpty(editable.toString()) || selectPathList.size() > 0 ){
					btn_send.setEnabled(true);
				}else{
					btn_send.setEnabled(false);
				}
			}
		});
	}


	@Override
	public void initData() {
		topicApi = new TopicApi(this);
		uploadApi = new UploadApi(this);
		topicId = getIntent().getStringExtra("topicId");
		UserPrefUtils prefUtils = new UserPrefUtils(this);
		user = prefUtils.getUser();
		selectPathList = new ArrayList<>();
		infos = new ArrayList<>();


		if(getIntent().hasExtra("clickreply")){
			iv_photo.setVisibility(View.GONE);
			clickreply = (Reply) getIntent().getSerializableExtra("clickreply");
			isReplyComment = getIntent().getBooleanExtra("isReplyComment",false);
			clickposition = getIntent().getIntExtra("clickposition",-1);
			see_old.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(GzTopicReplyTopicActivity.this,GzTopicDetailActivity.class);
					intent.putExtra("topicId", topicId);
					startActivity(intent);
				}
			});
			if(isReplyComment && clickreply.getUser()!=null){
				if (!TextUtils.isEmpty(clickreply.getUser().getId()+"")) {
					// 回复某条回复
					String startString = "回复 " + clickreply.getUser().getNick() + " :";
					et_sendreply.setText(startString);
					et_sendreply.setSelection(startString.length());

				}
			}
		}
	}


	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub 不可去掉
	}

	private void setEmojiconFragment(boolean useSystemDefault) {
		getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.emojicons,
						EmojiconsFragment.newInstance(useSystemDefault))
				.commit();
	}

	/**
	 * 表情处理
	 */
	@Override
	public void onEmojiconClicked(Emojicon emojicon) {
		EmojiconsFragment.input(et_sendreply, emojicon);
	}

	@Override
	public void onEmojiconBackspaceClicked(View v) {
		EmojiconsFragment.backspace(et_sendreply);
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_sendreply:
			emojiconslayout.setVisibility(View.GONE);
			ll_photo.setVisibility(View.GONE);
			showKeyboard();
			break;
		case R.id.linear:
			finish();
			break;
		case R.id.ll_back:
			Intent intent = new Intent();
			setResult(GzTopicMoreReplyActivity.REQUEST_CODE_BACK, intent);
			finish();
			break;
		case R.id.btn_send:
			closeKeyboard();
			content = et_sendreply.getText().toString().trim();
			if(TextUtils.isEmpty(content) && selectPathList.size()==0){
				showToast("请输入评论内容");
			}else{
				if(clickreply!=null){
					replyComment(content);
				}else{
					replyTopic(content);
				}
			}
			
			break;

		case R.id.iv_emoticons_normal:
			iv_keyboard_normal.setVisibility(View.VISIBLE);
			iv_emoticons_normal.setVisibility(View.GONE);
			closeKeyboard();
			emojiconslayout.setVisibility(View.VISIBLE);
			ll_photo.setVisibility(View.GONE);
			break;
		case R.id.iv_keyboard_normal:
			iv_keyboard_normal.setVisibility(View.GONE);
			iv_emoticons_normal.setVisibility(View.VISIBLE);
			emojiconslayout.setVisibility(View.GONE);
			ll_photo.setVisibility(View.GONE);
			et_sendreply.requestFocus();
			showKeyboard();
			break;
			
		case R.id.iv_photo:
			closeKeyboard();
			emojiconslayout.setVisibility(View.GONE);
			ll_photo.setVisibility(View.VISIBLE);
			break;

		case R.id.iv_select_photo:
			jumpSelectImage();
			break;

		case R.id.btn_set_mode_keyboard:
			emojiconslayout.setVisibility(View.GONE);
			ll_photo.setVisibility(View.GONE);
			et_sendreply.requestFocus();
			showKeyboard();
			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		onClick(ll_back);
	}

	/**
	 * 显示键盘
	 */
	private void showKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(et_sendreply, InputMethodManager.RESULT_SHOWN);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
				InputMethodManager.HIDE_IMPLICIT_ONLY);
	}

	private void closeKeyboard() {

		InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputmanger.hideSoftInputFromWindow(et_sendreply.getWindowToken(), 0);
//		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
//			if (getCurrentFocus() != null)
//				manager.hideSoftInputFromWindow(getCurrentFocus()
//						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == REQUEST_IMAGE){
			if(resultCode == RESULT_OK){
				selectPathList = (ArrayList<Image>) data.getSerializableExtra(MultiImageSelectorActivity.EXTRA_RESULT);
				Log.d("mSelectPath",selectPathList.size()+"--------------");
				if(selectPathList.size()>0){
					iv_select_photo.setVisibility(View.GONE);
					horizontal_listView.setVisibility(View.VISIBLE);
					tv_num.setVisibility(View.VISIBLE);
					tv_num.setText(selectPathList.size()+"");
					btn_send.setEnabled(true);
				}else{
					if(TextUtils.isEmpty(et_sendreply.getText().toString())){
						btn_send.setEnabled(false);
					}
					tv_num.setVisibility(View.GONE);
				}
				tv_image_num.setText("已选"+selectPathList.size()+"张，还可以添加"+
						(maxImageCount-selectPathList.size())+"张");
				commentImageAdapter.setSelectPathList(selectPathList);
				commentImageAdapter.notifyDataSetChanged();
			}
		}
	}

	private void replyTopic(String content) {
		if(TextUtils.isEmpty(topicId)) return ;

		try {
			PostsParam param = new PostsParam();
			param.setContent(content+"");
			param.setPostsId(topicId+"");
			param.setUserId(user.getId()+"");
			if (selectPathList.size() > 0) {
				param.setHasAlbum("1");
			} else {
				param.setHasAlbum("0");
			}
			topicApi.replyTopic(param, this);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void replyComment(String content){
		PostsParam param = new PostsParam();
		param.setContent(content);
		param.setPostsId(topicId+"");
		param.setUserId(user.getId()+"");
		param.setReplyId(clickreply.getId()+"");
		topicApi.replyComment(param, this);
	}

	@Override
	public void onStart(String tag) {
//		if(tag.equals(ApiConfig.APIURL.URL_POSTS_REPLYTOPIC)){
			showDialog("正在回复...",false);
//		}
	}

	@Override
	public void onSuccess(String response, String tag) {
		if (JSONHelper.isSuccess(response)) {
			if (tag.equals(ApiConfig.APIURL.URL_POSTS_REPLYTOPIC)) {
				ReplyCommentData replyCommentData = JsonUtil.getMode(response, ReplyCommentData.class);
				reply = replyCommentData.getData();
				reply.setUser(user);
				reply.setUpdateAt(System.currentTimeMillis());
				reply.setReplys(new ArrayList<Reply>());

				if (selectPathList.size() > 0) {
					setPostsAlbum(reply);
					new GzReplyImageUpload(GzTopicReplyTopicActivity.this,infos);
				}else{
					dismissDialog();
					Intent intent = new Intent();
					intent.putExtra("reply", reply);
					setResult(GzTopicDetailActivity.REQUEST_CODE_REPLYTOPIC, intent);
					finish();
				}
			}else if(tag.equals(ApiConfig.APIURL.URL_POSTS_REPLYCOMMNET)){
				ReplyCommentData replyCommentData = JsonUtil.getMode(response, ReplyCommentData.class);
				Reply reply = replyCommentData.getData();
				reply.setUser(user);
				reply.setUpdateAt(System.currentTimeMillis());
				dismissDialog();
				Intent intent = new Intent();
				intent.putExtra("reply", reply);
				intent.putExtra("clickposition",clickposition);
				setResult(GzTopicMoreReplyActivity.REQUEST_CODE_REPLYCOMMENT, intent);
				showToast("回复成功");
				finish();

			}
		}else{
			dismissDialog();
			showToast("回复失败");
		}
	}

	@Override
	public void onFaile(VolleyError volleyError, String tag) {
		dismissDialog();
		ResultCode.toastVolleyError(this, volleyError);
	}

	private void setPostsAlbum(Reply reply) {
		ArrayList<PostsAlbum> postsAlbums = new ArrayList<PostsAlbum>();
		for (int i = 0; i < selectPathList.size(); i++) {
			PostsAlbum postsAlbum = new PostsAlbum();
			postsAlbum.setThumbnail(selectPathList.get(i).path);
			postsAlbum.setUrl(selectPathList.get(i).path);
			if(selectPathList.get(i).isOri){
				postsAlbum.setOriUrl(selectPathList.get(i).path);
			}
			postsAlbums.add(postsAlbum);

			//保存到数据库
			ReplyImageInfo info = new ReplyImageInfo();
			info.setTopicId(topicId);
			info.setReplyId(String.valueOf(reply.getId()));
			info.setPath(selectPathList.get(i).path);
			info.setName(selectPathList.get(i).name);
			info.setUploadstate("false");
			if(selectPathList.get(i).isOri){
				info.setIsOri("true");
			}else{
				info.setIsOri("false");
			}
			infos.add(info);
//			DaoHelper.getInstance(this, EaseConstant.DB_NAME_REPLY_IMAGE).insert(info);
		}
		reply.setAlbums(postsAlbums);
	}

	// 图片上传完成
	@Subscribe
	public void uploadImgEvent(HashMap<String, Object> map) {
		String event = (String) map.get("event");
		if (BroadCastEvent.TOPICREPLYUPLOADIMG.equals(event)) {
			dismissDialog();
			String issuccess = (String) map.get("issuccess");
			if(issuccess.equals("true")){
				Reply reply = (Reply) map.get("reply");
				Intent intent = new Intent();
				intent.putExtra("reply", reply);
				setResult(GzTopicDetailActivity.REQUEST_CODE_REPLYTOPIC, intent);
				finish();
			}else{
				showToast("图片上传失败");
			}
		}
	}


	@Override
	public void addImage(int position) {
		if(position == selectPathList.size()){
			jumpSelectImage();
		}else{

		}

	}

	@Override
	public void close(int position) {
		selectPathList.remove(position);
		commentImageAdapter.setSelectPathList(selectPathList);
		commentImageAdapter.notifyDataSetChanged();
		tv_image_num.setText("已选"+selectPathList.size()+"张，还可以添加"+
				(maxImageCount-selectPathList.size())+"张");
		if(selectPathList.size()>0){
			horizontal_listView.setVisibility(View.VISIBLE);
			iv_select_photo.setVisibility(View.GONE);
			tv_num.setVisibility(View.VISIBLE);
			tv_num.setText(selectPathList.size()+"");
			btn_send.setEnabled(true);
		}else{
			tv_num.setVisibility(View.GONE);
			iv_select_photo.setVisibility(View.VISIBLE);
			horizontal_listView.setVisibility(View.GONE);
			if(TextUtils.isEmpty(et_sendreply.getText().toString())){
				btn_send.setEnabled(false);
			}
		}
	}

	private void jumpSelectImage(){
		int needToAddNumber2 = maxImageCount - selectPathList.size();
		if(needToAddNumber2<0){
			needToAddNumber2 = 0;
		}
		Intent intent = new Intent(GzTopicReplyTopicActivity.this, MultiImageSelectorActivity.class);
		// 是否显示拍摄图片
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
		// 最大可选择图片数量
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxImageCount);
		// 选择模式
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
		// 默认选择
		if(selectPathList != null && selectPathList.size()>0){
			intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectPathList);
		}
		startActivityForResult(intent, REQUEST_IMAGE);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).unregister(this);
	}


}
